import React, { useState, useEffect } from 'react';
import { is_empty, useCheck, CkValue, obj_empty, obj_str, IkInput, Dlg, useForm } from '../../nui';

/* lst: [
 *     {sn: "xx", name: "xx", ck: ck_empty, ckspace: true},
 * ]
*/
const DlgAdd = ({ hcmd, cur, open, setOpen, lst, title, name="" }) => {
    const [value, setValue] = useState();
    const form = useForm(setValue);
    const [ck_open, ckOpen, hcheck] = useCheck();

    useEffect(() => {
        if (!open) {
            return;
        }

        if (obj_empty(cur)) {
            setValue(null);
        }

        const tmp = {};
        lst.forEach(d => tmp[d.sn] = obj_str(cur, d.sn));

        setValue(tmp);
    }, [open, cur, lst]);

    const hok = () => {
        const ck = {};

        lst.forEach(d => {
            if (!d.ck) {
                return;
            }

            ck[d.sn] = v => d.ck(v, d.name);
        });

        if (!form.hcheck(ck, value)) {
            return;
        }

        setOpen(false);
        hcmd(cur, value);
    };

    const getDes = () => {
        if (is_empty(lst)) {
            return null;
        }

        const tmp = {};
        lst.forEach(d => {
            if (d.ckspace) {
                tmp[d.sn] = d.name;
            }
        });

        if (obj_empty(tmp)) {
            return null;
        }

        return tmp;
    };

    const getCtl = (d) => {
        return <IkInput key={d.sn} label={d.name} name={d.sn} form={form} value={value} className="mr-4"/>;
    };

    const getView = () => {
        if (is_empty(lst)) {
            return null;
        }

        return lst.map(d => getCtl(d));
    };

    return (
        <Dlg open={open} hcancel={() => setOpen(false)} title={title} hcmd={() => hcheck(value, getDes(), hok)} name={name}>
            <div className="flex flex-col">
                {getView()}
            </div>
            <CkValue open={ck_open} setOpen={ckOpen} value={value} setValue={setValue} des={getDes()} hcmd={hok}/>
        </Dlg>
    );
};

export {DlgAdd};
